package com.cxf.windex.base.rest;

import com.cxf.windex.base.biz.BaseBiz;
import com.cxf.windex.base.msg.ObjectRestResponse;
import com.cxf.windex.base.secruity.JwtTokenUtil;
import com.cxf.windex.base.secruity.JwtUser;
import com.cxf.windex.base.secruity.JwtUserFactory;
import com.cxf.windex.base.util.FileFilterTool;
import com.cxf.windex.entity.WeiUser;
import com.cxf.windex.rest.WeiLawyerController;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * @create 2017-06-15 8:48
 */
public class BaseController<Biz extends BaseBiz,Entity> {
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected Biz baseBiz;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    public static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * 文件存放 路径
     */
    @Value("${upload.path}")
    private String uploadPath;

    /**
     * 文件访问路径
     */
    @Value("${upload.url}")
    private String uploadUrl;

    @RequestMapping(value = "",method = RequestMethod.POST)
    @ResponseBody
    public ObjectRestResponse<Entity> add(Entity entity){
        baseBiz.insertSelective(entity);
        return new ObjectRestResponse<Entity>().rel(true);
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<Entity> get(@PathVariable Long id){
        return new ObjectRestResponse<Entity>().rel(true).result(baseBiz.selectById(id));
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    @ResponseBody
    public ObjectRestResponse<Entity> update(Entity entity){
        baseBiz.updateSelectiveById(entity);
        return new ObjectRestResponse<Entity>().rel(true);
    }
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public ObjectRestResponse<Entity> remove(@PathVariable Long id){
        baseBiz.deleteById(id);
        return new ObjectRestResponse<Entity>().rel(true);
    }

    @RequestMapping(value = "/all",method = RequestMethod.GET)
    @ResponseBody
    public List<Entity> list(){
        return baseBiz.selectListAll();
    }

    public void setCurrentUserName(WeiUser user){
        JwtUser userDetails= JwtUserFactory.create(user);

        String token= jwtTokenUtil.generateToken(userDetails);
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), userDetails.getAuthorities()); // 进行安全认证
        upToken.setDetails(userDetails);
        SecurityContextHolder.getContext().setAuthentication(upToken);
    }

    public String getCurrentUserName(){
        SecurityContext sc = SecurityContextHolder.getContext();
        if(sc.getAuthentication()==null){
            return "";
        }
        Object principal = sc.getAuthentication().getDetails();
        System.out.println("token:::" + principal.toString());
        if (principal instanceof JwtUser) {
            JwtUser user = (JwtUser) principal;

            return user.getUsername();
        }
        return "";
    }

    /**
     * 保存图片 返回Map
     * @param request
     * @param file 文件
     * @param type 文件类型
     * @return
     *   null 异常不处理
     *   -1  图片格式异常
     *   -2 图片保存异常
     *
     */
    public Map<String,String> saveFile(HttpServletRequest request,MultipartFile file,String type){
        if (file.isEmpty()) {
            return null;
        }
        FileFilterTool fileFilterTool=new FileFilterTool();
        if(!fileFilterTool.accept(file.getOriginalFilename())){
            return resultMap("-1","图片格式不正确。只能上传JPG,JPEG,GIF,PNG图片！");
        }
        try {
            String uuid= UUID.randomUUID().toString();
            String webRoot  = uploadPath  + File.separator  +type + File.separator+uuid+ File.separator;
            String saveUrl = uploadUrl+ "/" +type+ "/"+uuid+ "/"+ file.getOriginalFilename();

            File directoryFile = new File(webRoot);
            if(!directoryFile.exists()) {
                directoryFile.mkdirs();
            }
            logger.info("save path:"+webRoot);
            Path path = Paths.get(webRoot + file.getOriginalFilename());
            Files.write(path,  file.getBytes());
            Map<String, String> map = new HashMap<String, String>();
            map.put("filename",file.getOriginalFilename());
            map.put("saveUrl",saveUrl);
            map.put("code","0");
            logger.info("BankConfigController#saveFile processing : map= {},saveUrl={}", map,map.get("saveUrl"));
            return map;
        } catch (IOException e) {
            logger.error("BankConfigController#saveFile failed : IOException= {}", e);
            return resultMap("-2","图片保存异常！");
        }

    }
    /**
     * 返回结果信息
     *
     * @param code 0成功 -1失败
     * @param message 结算信息
     */
    public Map<String, String> resultMap(String code, String message) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("code", code);
        map.put("msg", message);
        return map;
    }
}
